<?php

namespace Framework\auth;

use Framework\auth\bean\JwtTokenConfigBean;
use Framework\auth\bean\RedisConfigBean;
use Framework\auth\exceptions\JwtException;
use Framework\utils\StringUtil;

/**
 * Trait Jwt
 * @package Framework\auth
 * @author 飞鸟与鱼
 */
trait Jwt
{
    /**
     * @var \Framework\auth\JwtAuth
     */
    protected $jwtAuth;

    /**
     * @var RedisConfigBean
     */
    protected $redisConfigBean;

    /**
     * @var JwtTokenConfigBean
     */
    protected $jwtTokenConfigBean;

    /**
     * @var \Framework\auth\interfaces\JwtUserInterface
     */
    protected $userModel;

    /**
     * @var string 当前访问的方法名称
     */
    protected $action;

    /**
     * 无需鉴权的方法
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 允许游客访问的方法
     * @var array
     */
    protected $allowVistor = [];

    public function auth($token)
    {
        $this->jwtAuth = new JwtAuth();
        if (!isset($this->redisConfigBean)) {
            $this->redisConfigBean = new RedisConfigBean();
        }
        if (!isset($this->jwtTokenConfigBean)) {
            $this->jwtTokenConfigBean = new JwtTokenConfigBean();
            $this->jwtTokenConfigBean->setVistorData($this->defaultVistorData());
        }
        $this->jwtAuth->setJwtUser($this->userModel);
        $this->jwtAuth->setJwtToken(new JwtToken($this->redisConfigBean, $this->jwtTokenConfigBean) );
        if (!$this->jwtAuth->match($this->action, $this->noNeedRight)) {
            $this->jwtAuth->auth($token);
        }
        if ($this->jwtAuth->isIsVisitor() && !$this->jwtAuth->match($this->action, $this->allowVistor)){
            throw new JwtException("当前为游客模式，无权限访问！", -10003);
        }
    }

    public function defaultVistorData()
    {
        return [
            'user_id' => '',
            'nickname' => "用户".StringUtil::random(),
            'age' => 18,
            'sex' => 1
        ];
    }
}